package com.jackrain.nea.oms.services;

import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.redis.CusRedisTemplate;
import com.jackrain.nea.util.RedisOpsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Discription: 新增或修改redis中缓存时间
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2018/5/17 17:03
 */
@Component
@Slf4j
public class UpdateRedisTimeService {

    public static final FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    public JSONObject updateRedisTime(String objid, String startTimeStr, String topicName, String spaceTime, String compay,  String layTime) {

        JSONObject retObj = new JSONObject();
        int code = 0;

        try {

            //开始时间
            if (startTimeStr == null || "".equals(startTimeStr) || startTimeStr.isEmpty()) {
                code = -1;
                retObj.put("code", code);
                retObj.put("errmsg", "请检查,STARTTIME 参数为空");
                return retObj;
            }

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(startTimeStr);
            Long startTime = date.getTime();

            if (objid.isEmpty() || topicName.isEmpty() || spaceTime.isEmpty() || compay.isEmpty() || layTime.isEmpty()) {
                // 有参数为空
                code = -1;
                retObj.put("code", code);
                retObj.put("errmsg", "请检查,参数为空");
                return retObj;
            }

            // 获取 redis 连接 , 相同key 会被覆盖
            CusRedisTemplate<String, String> redisTemplate = RedisOpsUtil.getStrRedisTemplate();

            //更新id
            redisTemplate.opsForHash().put(compay + "_TOPICTIME_ID", topicName, objid);
            //更新时间
            redisTemplate.opsForHash().put(compay + "_STARTTIME", topicName, String.valueOf(startTime));
            // 更新步长
            redisTemplate.opsForHash().put(compay + "_SPACETIME", topicName, spaceTime);
            //更新冗余时间
            redisTemplate.opsForHash().put(compay + "_LAYTIME", topicName, layTime);


            System.out.println(String.valueOf(redisTemplate.opsForHash().get(compay + "_STARTTIME", topicName)) + "redis中的 开始时间 ");

        } catch (Exception e) {
            // 修改
            code = -1;
            retObj.put("code", code);
            retObj.put("mssage", "修改 redis 缓存失败" + e.getCause() + e.getMessage());
            log.error(e.getMessage());
            return retObj;
        }

        retObj.put("code", code);
        retObj.put("mssage", "更新成功");
        return retObj;
    }

}
